package com.sealer.pattern.creational.singleton;

/**
 * Created by sealer on 17/03/29.
 * 第二种（懒汉，线程安全）
 * 这种写法能够在多线程中很好的工作，而且看起来它也具备很好的lazy loading，但是，遗憾的是，效率很低，99%情况下不需要同步。
 */
public class Singleton2 {
    private static Singleton2 instance;

    public Singleton2() {
    }

    //给整个方法加锁
    public static synchronized Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }


    //给new关键字加锁
    public static synchronized Singleton2 getInstance1() {
        if (instance == null) {
            synchronized (Singleton2.class) {
                instance = new Singleton2();
            }
        }
        return instance;
    }

    //给new关键字加锁 双重检查
    public static synchronized Singleton2 getInstance2() {
        if (instance == null) {
            synchronized (Singleton2.class) {
                if (instance == null) {//双重检查防止singleton在多线程的情况下占用多个空间
                    instance = new Singleton2();
                }
            }
        }
        return instance;
    }
}
